package com.example.testappwidget.ui.activity

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.widget.ImageView
import android.widget.RemoteViews
import android.widget.TextView
import android.widget.ViewFlipper
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.example.testappwidget.R
import com.example.testappwidget.utils.LogUtil
import com.example.testappwidget.utils.StringUitl
import com.example.testappwidget.utils.WidgetSizeProvider
import com.example.testappwidget.widgetprovider.NewBatteryWidget
import com.example.testappwidget.widgetprovider.StateWidget
import com.example.testappwidget.widgetprovider.TestWidget

/*
https://blog.csdn.net/lwzhang1101/article/details/101429143

https://blog.csdn.net/hwb04160011/article/details/119728412

https://blog.csdn.net/weixin_35691921/article/details/131182266

官网widget
https://developer.android.com/develop/ui/views/appwidgets/configuration?hl=zh-cn

Android所有应用widget以列表形式显示
https://blog.csdn.net/raolulu/article/details/120869901

服务
https://blog.csdn.net/c19344881x/article/details/129060604

已解决】Android12以上PendingIntent需要强制增加FLAG_IMMUTABLE或FLAG_MUTABLE
https://blog.csdn.net/burly/article/details/129296597

PendingIntent重定向：一种针对安卓系统和流行App的通用提权方法
https://segmentfault.com/a/1190000041550819?utm_source=sf-similar-article

 */
class MainActivity : AppCompatActivity() {
    private lateinit var tvAdd: TextView

    //    private lateinit var tvInfo: TextView
    private lateinit var tvUpdate: TextView
    private lateinit var tvMyStateValue: TextView
    private lateinit var myEmo: ImageView
    private lateinit var tvFriednStateValue: TextView
    private lateinit var tvUpdateTime: TextView
    private lateinit var viewFlipper: ViewFlipper
    private lateinit var appWidgetManager: AppWidgetManager
    private val Tag = this.javaClass.simpleName
    var count = 0

    companion object {
        const val key_mystate = "mystate"
        const val key_friendstate = "friendstate"
        const val key_updatetime = "updatetime"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initview()
        initviewFlipper()
        initData()
        initEvent()
        val EXTRA_APPWIDGET_ID = intent?.extras?.getInt(
            AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID
        )

        val key1_value = intent?.extras?.getString(TestWidget.key_1)
        LogUtil.i(Tag, "onCreate 回调 EXTRA_APPWIDGET_ID = $EXTRA_APPWIDGET_ID , key1_value = $key1_value")
        savedInstanceState?.let {
            val key_1_value = it.getString(TestWidget.key_1)
            val key_2_value = it.getString(TestWidget.key_2)
            val EXTRA_APPWIDGET_ID = it.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID)
            LogUtil.i(
                Tag,
                "回调 onCreate  key_1_value = ${key_1_value}, key_2_value = ${key_2_value}， EXTRA_APPWIDGET_ID = $EXTRA_APPWIDGET_ID"
            )

//            val mystate_value = it.getString(key_mystate)
//            val friendstate_value = it.getString(key_friendstate)
//            val updatetime_value = it.getString(key_updatetime)
//            if (mystate_value.isNullOrEmpty()){
//                return
//            }
//            updateStateWidget(mystate_value, friendstate_value, updatetime_value)

        }


//        val widgetSizeProvider = WidgetSizeProvider(this)

//        val pair = widgetSizeProvider.getWidgetsSize(73)
//        val pair = widgetSizeProvider.getWidgetsSize(22)
        //程序日志信息 ---> 宽高 pair = (640, 346)
        // 320 dp 173dp
//        LogUtil.i(Tag, "宽高 pair = ${pair}")

    }

    private fun initviewFlipper() {
        viewFlipper = findViewById(R.id.viewFlipper)
        val images = arrayOf(
            R.mipmap.img01_01,
            R.mipmap.img01_02,
            R.mipmap.img02_01,
            R.mipmap.img02_02,
            R.mipmap.img03_01,
            R.mipmap.img03_02
        )
        viewFlipper.removeAllViews()
        images.forEach {
            val itemImageViewRoot = layoutInflater.inflate(R.layout.item_img, viewFlipper, false)
            val ivItemImage = itemImageViewRoot.findViewById<ImageView>(R.id.ivItemImage)
            ivItemImage.setImageResource(it)
            viewFlipper.addView(itemImageViewRoot)
        }



    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        LogUtil.i(Tag, "onNewIntent intent == null = ${intent == null}")

        if (intent == null) {
            return
        }

        intent.extras?.let {
            val key_1_value = it.getString(TestWidget.key_1)
            val EXTRA_APPWIDGET_ID = it.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID)
            LogUtil.i(
                Tag,
                "回调 onNewIntent  key_1_value = ${key_1_value}, EXTRA_APPWIDGET_ID = $EXTRA_APPWIDGET_ID"
            )
        }

    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        LogUtil.i(
            Tag,
            "onRestoreInstanceState savedInstanceState == null = ${savedInstanceState == null}"
        )
        savedInstanceState?.let {
            val key_1_value = it.getString(TestWidget.key_1)
            val key_2_value = it.getString(TestWidget.key_2)
            LogUtil.i(
                Tag,
                "回调 onRestoreInstanceState  key_1_value = ${key_1_value}，key_2_value = ${key_2_value}"
            )
        }
    }


    override fun onSaveInstanceState(outState: Bundle) {
        outState.putString(TestWidget.key_2, "存储数据")
        super.onSaveInstanceState(outState)
        val key1_value = outState.getString(TestWidget.key_1)
        val EXTRA_APPWIDGET_ID = outState.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID)
        LogUtil.i(
            Tag,
            "onSaveInstanceState key1_value = ${key1_value}, EXTRA_APPWIDGET_ID = $EXTRA_APPWIDGET_ID"
        )
    }

    private fun initData() {
        appWidgetManager = AppWidgetManager.getInstance(this)
        updateStateWidget(null, null, null)
    }

    private fun initview() {
        tvAdd = findViewById(R.id.tvAdd)
//        tvInfo = findViewById(R.id.tvInfo)
        tvUpdate = findViewById(R.id.tvUpdate)
        tvMyStateValue = findViewById(R.id.tvMyStateValue)
//        myEmo = findViewById(R.id.myEmo)
        tvFriednStateValue = findViewById(R.id.tvFriendSateValue)
        tvUpdateTime = findViewById(R.id.tvUpdateTime)


//       val animationDrawable =  myEmo.background as AnimationDrawable
//        animationDrawable.isOneShot = false
//        animationDrawable.start()

    }

    private fun initEvent() {
        tvAdd.setOnClickListener {
            /*
                官网
                允许用户固定 widget
                在搭载 Android 8.0（API 级别 26）及更高版本的设备上，允许用户创建固定快捷方式的启动器还可让用户将 widget 固定到主屏幕上。
                与固定快捷方式类似，这些固定的 widget 让用户能够访问应用中的特定任务，并且可以直接从应用添加到主屏幕，
             */
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                return@setOnClickListener
            }

            if (appWidgetManager.isRequestPinAppWidgetSupported) {
                //已解决】Android12以上PendingIntent需要强制增加FLAG_IMMUTABLE或FLAG_MUTABLE
                //https://blog.csdn.net/burly/article/details/129296597

//                addNewBatteryWidget()
                addTestWidget()
//                addStateWidget()
            }

        }

//        tvInfo.setOnClickListener {
//            startActivity(Intent(this, NewBatteryInfoActivity::class.java))
//        }

        tvUpdate.setOnClickListener {
//            updateStateWidget()
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun addNewBatteryWidget() {
        val successCallback = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            PendingIntent.getBroadcast(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
        } else {
            PendingIntent.getBroadcast(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        }
        val myProvider = ComponentName(this, NewBatteryWidget::class.java)
        appWidgetManager.requestPinAppWidget(myProvider, null, successCallback)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun addTestWidget() {


        val testWigetProvider = ComponentName(this, TestWidget::class.java)


        val appWidgetIds = appWidgetManager.getAppWidgetIds(testWigetProvider)
//        appWidgetIds?.also {
//            for ((index, item) in it.withIndex()){
//                LogUtil.i(Tag,"appWidgetIds = ${item}")
//                val views = RemoteViews(this.packageName, R.layout.test_appwidget)
//                views.setTextViewText(R.id.tv, "Main更新数据${count++}")
//                appWidgetManager.updateAppWidget(item,views)
//                //2024-04-02 15:52:39.381 21700-21700 MainActivity            com.example.testappwidget            I   程序日志信息 ---> appWidgetIds = 30
//                //2024-04-02 15:52:39.381 21700-21700 MainActivity            com.example.testappwidget            I   程序日志信息 ---> appWidgetIds = 31
//            }
//        }

        if (appWidgetIds.size > 0){// 更新组件
            val views = RemoteViews(this.packageName, R.layout.test_appwidget)
            views.setTextViewText(R.id.tv, "更新数据${count++}")
            appWidgetManager.updateAppWidget(appWidgetIds[0],views)
            return
        }


        val bundle = Bundle()
        bundle.putString(TestWidget.key_1, "mainactivity 安装 testWiget 组件")

        val successCallback = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_IMMUTABLE
            )
        } else {
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        }

        appWidgetManager.requestPinAppWidget(testWigetProvider, bundle, successCallback)

    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun addStateWidget() {
        val testWigetProvider = ComponentName(this, StateWidget::class.java)


        val bundle = Bundle()
        bundle.putString(TestWidget.key_1, "mainactivity 安装 state_widget 组件")

        val successCallback = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_IMMUTABLE
            )
        } else {
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        }

//        appWidgetManager.requestPinAppWidget(testWigetProvider, bundle, successCallback)
        appWidgetManager.requestPinAppWidget(testWigetProvider, bundle, null)
    }

    private fun updateStateWidget(mystate: String?, friendstate: String?, updateTime: String?) {
        if (intent == null) {
            LogUtil.i(Tag, "updateStateWidget intent == null")
            return
        }

        if (intent.extras == null) {
            LogUtil.i(Tag, "updateStateWidget intent.extras == null")

            return
        }

        intent.extras!!.apply {
            val mystate_value: String? = getString(key_mystate)
            val friendstate_value: String? = getString(key_friendstate)
            val updatetime_value: String? = getString(key_updatetime)
            tvMyStateValue.setText(mystate_value)
            tvFriednStateValue.setText(friendstate_value)
            tvUpdateTime.setText(updatetime_value)
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun updateStateWidget() {

        val mystate = "思考${count++}"
        val friendstate = "发呆${count++}"
        var updateTime = "更新时间:${StringUitl.timeStamp2DateYMDHMS(System.currentTimeMillis())}"
        val testWigetProvider = ComponentName(this, StateWidget::class.java)

        tvMyStateValue.setText(mystate)
        tvFriednStateValue.setText(friendstate)
        tvUpdateTime.setText(updateTime)

        val appWidgetIds = appWidgetManager.getAppWidgetIds(testWigetProvider)
        appWidgetIds?.also {
            for ((index, item) in it.withIndex()) {
                LogUtil.i(Tag, "appWidgetIds = ${item}")
                val views = RemoteViews(this.packageName, R.layout.layout_state_widget_view_medium1)
                views.setTextViewText(R.id.tvMyStateValue, mystate)
                views.setTextViewText(R.id.tvFriendSateValue, friendstate)
                views.setTextViewText(R.id.tvUpdateTime, updateTime)
                views.setTextColor(R.id.tvMyStateValue, Color.parseColor("#ff0000"))
                views.setTextColor(R.id.tvFriendSateValue, Color.parseColor("#ff0000"))
                views.setTextColor(R.id.tvUpdateTime, Color.parseColor("#ff0000"))
                appWidgetManager.updateAppWidget(item, views)

                val widgetSizeProvider = WidgetSizeProvider(this)

//        val pair = widgetSizeProvider.getWidgetsSize(73)
                val pair = widgetSizeProvider.getWidgetsSize(item)
                //程序日志信息 ---> 宽高 pair = (640, 346)
                // 320 dp 173dp
                LogUtil.i(Tag, "appWidgetIds = ${item} 宽高  pair = ${pair}")


            }
        }

        if (appWidgetIds.size > 0) {// 更新组件
//            val views = RemoteViews(this.packageName, R.layout.layout_state_widget_view_medium1)
//            views.setTextViewText(R.id.tv, "更新数据${count++}")
//            appWidgetManager.updateAppWidget(appWidgetIds[0],views)
            return
        }


        val bundle = Bundle()
        bundle.putString(TestWidget.key_1, "mainactivity 安装 testWiget 组件")

        val successCallback = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_MUTABLE
            )
        } else {
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        }

//        appWidgetManager.requestPinAppWidget(testWigetProvider,bundle, successCallback)
        appWidgetManager.requestPinAppWidget(testWigetProvider, bundle, null)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtil.i(Tag, "onActivityResult data == null ${data == null}")
        if (data == null) {
            return
        }

        data.extras?.let {
            val key_1_value = it.getString(TestWidget.key_1)
            LogUtil.i(Tag, "回调 onNewIntent  key_1_value = ${key_1_value}")
        }
    }
}